#include<iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include<sys/types.h>
#include<sys/socket.h>
#include"Thread.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace ThreadModule;
void Usage(std::string process)
{
    std::cout<<"Uage:\n\t" << process << "serverip serverport\n"<<std::endl;
}
int InitClient(std::string serverip,uint16_t serverport,struct sockaddr_in* serveraddr)
{
    //1. 创建socket
    //int socket(int domain, int type, int protocol);   domain: IPv4 Internet protocols  type:Supports datagrams (connectionless, unreliable messages of a fixed maximum length).
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        std::cerr<<"socket error"<<std::endl;
    }
    // 2. client要不要bind？一定要，client也要有自己的IP和PORT。要不要显式[和server一样用bind函数]的bind？不能！不建议！！
    // a. 如何bind呢？udp client首次发送数据的时候，OS会自己自动随机的给client进行bind --- 为什么？防止client port冲突。要bind，必然要和port关联！
    // b. 什么时候bind呢？首次发送数据的时候
    //2. 构建目标主机socket信息
    memset(serveraddr, 0, sizeof(struct sockaddr_in));
    serveraddr->sin_family = AF_INET;
    serveraddr->sin_port = htons(serverport); //host to network short
    serveraddr->sin_addr.s_addr = inet_addr(serverip.c_str());//将十进制点分十进制 转换为 网络序列
    return sockfd;
}
void recvmessage(int sockfd, std::string name)
{
    while(true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd,buffer,sizeof(buffer)-1,0 ,(struct sockaddr*)&peer,&len);
        if(n > 0)
        {
            buffer[n] = 0;
            fprintf(stderr,"[%s]%s\n",name.c_str(),buffer);
        }
    }
}
void sendmessage(int sockfd,struct sockaddr_in& serveraddr, std::string name)
{
    std::string message;
    while(true)
    {
        printf("%s | Enter#",name.c_str());
        fflush(stdout);
        std::getline(std::cin,message);
        sendto(sockfd,message.c_str(),message.size(),0, (struct sockaddr*)&serveraddr,sizeof(serveraddr));
    }
}
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in serveraddr;
    std::cout<<"debug1"<<std::endl;

    int sockfd = InitClient(serverip,serverport,&serveraddr);
    std::cout<<"debug2"<<std::endl;

    func_t r = std::bind(&recvmessage,sockfd,std::placeholders::_1);
    func_t s = std::bind(&sendmessage,sockfd,serveraddr,std::placeholders::_1);

    Thread Recver(r,"recver");
    Thread Sender(s,"sender");
    Recver.Start();
    Sender.Start();
    std::cout<<"debug3"<<std::endl;


                                                     
    Recver.Join();
    Recver.Join();

    return 0;
}